package kook.util;

import java.util.Map;
import java.util.Objects;

public class TemplateUtils {
    public static String replaceParamsForCurlyBrace(String origin, Map<String, Object> map) {
        StringBuilder sb = new StringBuilder(origin);
        replaceParams(sb, 0, map, '{', '}');
        return sb.toString();
    }

    private static void replaceParams(StringBuilder sb, int start, Map<String, Object> map, char leftToken, char rightToken) {
        StringBuilder key = new StringBuilder();
        for (int i = start; i < sb.length(); i++) {
            char c = sb.charAt(i);
            if (!key.isEmpty()) {
                key.append(c);
                if (c == rightToken) {
                    String k = key.toString();
                    k = k.substring(1, k.length() - 1);
                    if (!map.containsKey(k)) {
                        key.setLength(0);
                        continue;
                    }
                    String v = Objects.toString(map.get(k), "");
                    // System.out.println(key.toString());
                    int right = i + 1;
                    int left = right - key.length();
                    sb.delete(left, right);
                    sb.insert(left, v);
                    // System.out.println(sb);
                    // System.out.println(sb.charAt(left + "啊啊?".length()));
                    replaceParams(sb, left + v.length(), map, leftToken, rightToken);
                    break;
                }
            }
            if (c == leftToken) {
                key.append(c);
            }
        }
    }
}
